/* Copyright (C) Abu Rizal, 2009.
 * 
 * This file is part of QurText.
 * 
 * QurText is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * QurText is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with QurText. If not, see <http://www.gnu.org/licenses/>.
 */
package qurtext.factory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;

import javax.jdo.PersistenceManager;

import qurtext.domain.Verse;

public class VerseFactory {

	@SuppressWarnings("unchecked")
	public List<Verse> getSectionVerseList(int chapterNo, int verseNo, int endVerseNo) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + Verse.class.getName() + " where chapterNo==" + chapterNo + " && verseNo>=" + verseNo + " && verseNo<=" + endVerseNo;
			List<Verse> resultList = new ArrayList<Verse>();
			resultList.addAll((Collection<Verse>) pm.newQuery(query)
					.execute());
			return resultList;
		} finally {
			pm.close();
		}
	}

	public Verse getBasmallah() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Verse result = getVerse(pm, 1, 1);
			return result;
		} catch (NoSuchElementException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	private Verse getVerse(PersistenceManager pm, int chapterNo, int verseNo) {
		String query = "select from " + Verse.class.getName() + " where chapterNo==" + chapterNo + " && verseNo==" + verseNo;
		Verse result = ((Collection<Verse>) pm.newQuery(query)
				.execute()).iterator().next();
		return result;
	}
}
